package com.adv.ems.filters.original.after;

import cn.hutool.core.collection.CollectionUtil;
import com.adv.ems.db.entity.EnergyDataCumulateDO;
import com.adv.ems.filters.EnergyDataBaseFilter;
import com.adv.ems.filters.dto.FilterParam;
import com.adv.ems.filters.original.dto.OriginalDealAfterDTO;
import com.adv.ems.manager.ReportHourPoolManager;
import com.adv.ems.model.vo.ResultVO;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class MarkReportHourAfterFilter extends EnergyDataBaseFilter<OriginalDealAfterDTO, Boolean> {
    @Resource
    ReportHourPoolManager reportHourPoolManager;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");

    @Override
    protected String getFilterName() {
        return "数据小时报表池写入";
    }

    @Override
    protected double getOrder() {
        return 1;
    }

    @Override
    protected boolean isBefore() {
        return false;
    }

    @Override
    protected String getType() {
        return OriginalDealAfterDTO.class.getName();
    }

    @Override
    protected ResultVO<Boolean> handle(FilterParam<OriginalDealAfterDTO> param) {
        OriginalDealAfterDTO dealAfter = param.getList().get(0);
        List<EnergyDataCumulateDO> cumulate = dealAfter.getCumulate();
        if (CollectionUtil.isEmpty(cumulate)) {
            return ResultVO.success();
        }
        Map<Long, Set<String>> colHours = new HashMap<>();
        cumulate.forEach(c -> {
            Set<String> orDefault = colHours.getOrDefault(c.getCollectPointId(), new HashSet<>());
            orDefault.add(sdf.format(c.getColDate()));
            colHours.put(c.getCollectPointId(), orDefault);
        });
        for (Map.Entry<Long, Set<String>> entry : colHours.entrySet()) {
            Long pointId = entry.getKey();
            entry.getValue().forEach(s -> {
                try {
                    Date date = sdf.parse(s);
                    reportHourPoolManager.saveOrUpdate(pointId, date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        return ResultVO.success();
    }
}
